package com.yzt.insys.control;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.mvc.UrlFilenameViewController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yzt.insys.common.Constants;
import com.yzt.insys.common.PageNavation;
import com.yzt.insys.dto.UserDto;
import com.yzt.insys.interceptor.CustomTimestampEditor;
import com.yzt.insys.interceptor.DateConvertEditor;

/**
 * @作者 zsf
 * @时间 2013-6-20
 */
public class BaseControl extends UrlFilenameViewController{
	
	protected final Log logger = LogFactory.getLog(getClass());
	protected static final String ENCODEING =Constants.ENCODEING;
    protected static Map<String,Object> paramMap=null;
    protected static List<Object> paramList;
    protected static final String INDEX="redirect:/goLogin";
    protected static String forward="";
    protected static String msg=null;
    
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session ;
    
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request,HttpServletResponse response){
    	this.request=request;
    	this.response=response;
    	this.session=request.getSession();
    	getParamMap();
    	paramList=new ArrayList<Object>();
    }
    /**
	 * 日期转换
	 *
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Timestamp.class,new DateConvertEditor("yyyy-MM-dd HH:mm:ss"));
		binder.registerCustomEditor(Date.class,"replyTime",new DateConvertEditor());
		binder.registerCustomEditor(Date.class,"birthDay",new DateConvertEditor());
		binder.registerCustomEditor(Date.class, new DateConvertEditor());  
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
		
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		
		DateFormat dateTimeFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateTimeFormat.setLenient(false);
		
		binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat,true));
		binder.registerCustomEditor(Timestamp.class,new CustomTimestampEditor(dateTimeFormat,true));
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
	}
	
    protected void writeStr2Client(String str) throws IOException {
        response.setContentType("text/plain;charset=" + ENCODEING);
        PrintWriter writer = response.getWriter();
        writer.write(str);
        writer.flush();
        writer.close();
    }

    /**
     * 获取request传递过来的参数
     * @return
     */
    public Map<String,Object> getParamMap(){
    	paramMap= new HashMap<String, Object>();
		@SuppressWarnings("unchecked")
		Enumeration<String> paramNames =request.getParameterNames();
		String paramName = "";
		String paramValue = "";
		while (paramNames.hasMoreElements()) {
			paramName = paramNames.nextElement();
			paramValue = request.getParameter(paramName);
			paramMap.put(paramName, paramValue);
		}
		paramMap.put("path",getPath());
		return paramMap;
    }

    /**
     * 从session中获取user
     * @return
     */
    public UserDto getUserFromSession(){
    	Object attribute = session.getAttribute(Constants.USER_KEY_IN_SESSION);
		return attribute == null ? null : (UserDto) attribute;
    }
    
    /**
     * 获取将要删除的ids和deletedBy
     * @param ids
     * @return
     */
    protected Map<String,Object> getDeletedMap(List<Long> ids){
    	paramMap.clear();
		paramMap.put("deletedBy",getUserFromSession().getId());
		paramMap.put("ids",ids);
		return paramMap;
    }
    /**
     * 获取page,page中设置的值有pageSize=10000,startIndex=0,order=ASC
     * @return
     */
    protected PageNavation getPage(){
    	PageNavation page=new PageNavation();
		page.setPageSize(10000);
		page.setStartIndex(0);
		page.setOrder("ASC");
		return page;
    }
    /**
     * 将信息(key/value)保存到request中
     * @param key
     * @param value
     */
    protected void reqAddAttr(String key,Object value){
    	request.setAttribute(key, value);
    }
    
    /**
     * 将信息(key/value)保存到session中
     * @param key
     * @param value
     */
    protected void sesAddAttr(String key,Object value){
    	session.setAttribute(key, value);
    }
    
    /**
     * 将信息(kek/value)从session中删除
     * @param key
     */
    protected void sesDelAttr(String key){
		session.removeAttribute(key);
	}
    
    /**
     * 将对象转换成json，date类型将转换成yyyy-MM-dd HH:mm:ss格式
     * @param object 需要转换成json格式的对象
     * @return
     */
    protected String toJSONStringWithDateFormat(Object object){
    	return JSON.toJSONStringWithDateFormat(object,"yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteDateUseDateFormat);
    }
    
    /**
     * 将对象转换成json
     * @param object	需要转换成json格式的对象
     * @param dateformat 日期格式，如果为null,则默认为yyyy-MM-dd HH:mm:ss格式
     * @return
     */
    protected String toJSONStringWithDateFormat(Object object,String dateformat){
    	if(dateformat==null){
    		return toJSONStringWithDateFormat(object);
    	}
    	return JSON.toJSONStringWithDateFormat(object,dateformat,SerializerFeature.WriteDateUseDateFormat);
    }
    
    /**
     * 获取当前访问的path
     * @return
     */
    public String getPath(){
    	String path = getViewNameForRequest(request);
    	if(path.contains("/")){
    		path = path.substring(0, path.indexOf("/"));    		
    	}
		return path;
    }
    
    /**
     * 转向到toAdd页面
     * @return
     */
    protected String forward_toAdd(){
    	return "menu/"+getPath()+"/toAdd";
    }
    
    /**
     * 转向到toUpd页面
     * @return
     */
    protected String forward_toUpd(){
    	return "menu/"+getPath()+"/toUpd";
    }
    
    /**
     * 转向到view页面
     * @return
     */
    protected String forward_toView(){
    	return "menu/"+paramMap.get("path")+"/view";
    }
	@Override
	protected String getViewNameForRequest(HttpServletRequest request) {
		this.request=request;
		return super.getViewNameForRequest(request);
	}
    
    
}
